<template>
  <div class="corneal">
    <Echarts/>
    <el-col class="col1" style="margin-right: 1%;margin-left: 2%">
      <el-card class="card1" style="width: 100% ;height:227px" >
        <div  @click="handleUploadSuccess">
          <el-upload
            accept=".png,.jpg,.jpeg,.tif"
            ref="uploadFile"
            class="upload-demo"
            :http-request="postImgOfMy"
            :before-upload="getCurrentTime"
            :action="url.upload"
            :name="url.upload_img_name"
            :data="url.upload_data"
            :file-list="fileList"
            :show-file-list="false"
            drag
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__tip">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" >能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </div>
      </el-card>
      <el-card class="card2" style="width: 100%">
        <!--  图片文件列表    -->
        <el-col>
          <div>
            <el-input
              placehholder="请输入文件名称"
              clearable
              prefix-icon="el-icon-search"
              v-model="qqq"
              style="width: 100%"
            />
          </div>
<!--          <div>已经上传: {{ has_upload_count }}, 总数量{{ has_upload_count2 }}, 小水管请等待</div>-->
          <div><el-progress :text-inside="true" :stroke-width="17" :percentage="setItemProgress(this.has_upload_count,this.has_upload_count2)" v-if="!isNaN(parseInt((this.has_upload_count/this.has_upload_count2)*100))"
            :status="setItemStatus(this.has_upload_count,this.has_upload_count2)" :format="setItemText(this.has_upload_count,this.has_upload_count2,this.has_upload_fail)"></el-progress></div>
          <el-tabs v-model="activeName" @tab-click="handleClick" style="width: 100%">
            <el-tab-pane label="成功列表" name="first">
              <div class="head-container">
                <el-container style="height: 500px; border: 1px solid #eee">
                  <el-main>
                    <el-tree
                      ref="tree"
                      default-expand-all
                      highlight-current
                      :data="tree_data"
                      :filter-node-method="filterNode"
                    >
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                      <span>{{ node.label | ellipsis}}</span>
                      <span>
                        <el-button
                          type="text"
                          size="mini"
                          @click="image_get(node,data)">
                          查看结果
                        </el-button>
                        <el-button
                          type="text"
                          size="mini"
                          @click="() => remove(node, data)">
                          删除
                        </el-button>
                      </span>
                    </span>
                    </el-tree>
                  </el-main>
                </el-container>
              </div>
            </el-tab-pane>
            <el-tab-pane label="失败及其原因" name="second">
              <el-container  style="height: 500px; width: 350px; border: 1px solid #eee">
                <el-main>
                  <el-table
                    :data="tableData"
                    style="width: 100%">
                    <el-table-column
                      prop="file_name"
                      label="文件名"
                      width="150">
                    </el-table-column>
                    <el-table-column
                      prop="message"
                      label="信息"
                      width="150">
                    </el-table-column>
                  </el-table>
                </el-main>
              </el-container>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-card>
    </el-col>
    <!--  下拉框    -->
    <el-col class="col2" style="margin-right: 2%;margin-left: 1%">
      <el-card class="card3" style="width: 100%; height:150px">
          <el-col class="body1">
            <el-col class="button1" >
              <el-form class="fontclass" ref="queryForm" size="small" :inline="true" label-width="68px" >
                <el-tooltip class="item" effect="dark" content="1.点击上传图片 2.点击开始处理 3.处理完成再点击下载和导出" placement="top">
                  <el-button size="small">操作说明</el-button>
                </el-tooltip>
                <span class="one"
                >微信打开，正常使用即可</span>
              </el-form>
              <el-form ref="queryForm" size="small" :inline="true" label-width="68px">
                <el-form-item label="用户名称" prop="userName" label-width="80px">
                  <el-input
                    placeholder="用户名"
                    v-model="users_name"
                    clearable
                    style="width: 110px"
                  />
                </el-form-item>
                <el-form-item label="当前图片名称" prop="fileName" label-width="100px">
                  <el-select
                    placeholder="选择图片"
                    v-model="search_id"
                    clearable
                    style="width: 200px"
                  >
                    <el-option
                      v-for="item in tree_data"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      @click.native="image_get(tree_data[search_id])"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item >
                  <el-button type="primary"  size="mini" @click="predictStateMonitor" :loading="load">{{ this.left_time }}</el-button>
                </el-form-item>
              </el-form>
              <el-form ref="queryForm" size="small" :inline="true" label-width="68px">
                <el-form-item label="图像增强" prop="status" label-width="80px" >
                  <el-select
                    v-model="deal_request.enhance_choice"
                    placeholder="选择增强模型"
                    clearable
                    style="width: 110px"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="角膜神经分割" prop="status"  label-width="100px">
                  <el-select
                    v-model="deal_request.segmentation_choice"
                    placeholder="选择分割模型"
                    clearable
                    style="width: 200px"
                  >
                    <el-option
                      v-for="item in option1"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      :disabled="item.disabled">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
<!--                  <el-button type="primary"   size="mini"  @click="image_download" :loading="load2">{{ this.left_time2 }}</el-button>-->
                  <el-dropdown @command="handleCommand" >
                    <el-button type="primary"   size="mini"   :loading="load2">{{ this.left_time2 }}
                      <i class="el-icon-arrow-down el-icon--right"></i></el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="a">中文下载</el-dropdown-item>
                      <el-dropdown-item command="b">英文下载</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                  <el-dialog
                    title="下载提示"
                    :visible.sync="dialogVisible"
                    width="30%">
                    <el-table :data="gridData" class= "fontclass" max-height="800" >
                      <el-table-column property="filename" label="文件名" width="150" ></el-table-column>
                      <el-table-column property="content" label="内容" width="250"></el-table-column>
                    </el-table>
                  </el-dialog>
                </el-form-item>
              </el-form>
              <el-form ref="queryForm" size="small" :inline="true" label-width="68px">
                <el-form-item label="血管量化" prop="status" label-width="80px">
                  <el-select
                    v-model="deal_request.vascular_choice"
                    placeholder="选择模型"
                    clearable
                    style="width: 110px"
                  >
                    <el-option
                      v-for="item in option3"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="弯曲度分级" prop="status" label-width="100px">
                  <el-select
                    v-model="deal_request.grade_choice"
                    placeholder="选择模型"
                    clearable
                    style="width: 200px"
                  >
                    <el-option
                      v-for="item in option2"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item >
                  <el-button type="primary" size="mini" @click="btnClickExport" :loading="load3">{{ this.left_time3 }}</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-col>
      </el-card>
      <el-card class="card4" style="width: 100%">
        <el-tabs v-model="currentPage1" type="card" @tab-click="handleClick">
          <el-tab-pane label="角膜神经分割、弯曲度分级等任务" name="1">
            <Allresult
              :url_org="url_org"
              :url_enh="url_enh"
              :url_seg_org="url_seg_org"
              :url_seg_enh="url_seg_enh"
              :url_seg2_org="url_seg2_org"
              :url_seg2_enh="url_seg2_enh"
              :url_grade_org="url_grade_org"
              :url_grade_enh="url_grade_enh"
              :level_org="level_org.level"
              :level_org1="level_org.probabilities"
              :level_enh="level_enh.level"
              :level_enh1="level_enh.probabilities"
              :url_color_org="url_color_org"
              :url_color_enh="url_color_enh"
              :url_point_org="url_point_org"
              :url_point_enh="url_point_enh"
              :url_seg3_org="url_seg3_org"
              :url_seg3_enh="url_seg3_enh"
              :vascular_org="vascular_org"
              :vascular_enh="vascular_enh"
              :json1="json1"
              :json2="json2"
              :search_img_name="search_img_name"/>
          </el-tab-pane>
          <el-tab-pane label="量化指标" name="2">
            <el-row class="charts">
              <div class="st">
                <div id="prob" style="width: 420px;
                 height: 200px;
                 fontSize:25px;
                 padding-left:5px" ></div>
              </div>
              <div class="st">
                <div id="prob1" style="width: 420px;
                 height: 200px;
                 fontSize:25px;
                 padding-left:5px" ></div>
              </div>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-col>
    <!--    </el-col>-->
  </div>
</template>
<script>
/* eslint-disable */
import { LimitAxiosPost } from '@/api/limit_axios'

import axios from 'axios'
import Allresult from './allresult.vue'
import Echarts from './Echarts'
import XLSX from 'xlsx';
// eslint-disable-next-line no-unused-vars
let echarts = require('echarts/lib/echarts')
// 引入柱状图组件
require('echarts/lib/chart/line')
// 引入提示框和title组件
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')

export default {
  components: { Echarts, Allresult },
  data () {
    return {
      search_value:0,
      gridData: [{
        filename: 'Enhance',
        content: '增强图处理结果',
      }, {
        filename: 'Normal',
        content: '原图处理结果',
      }, {
        filename: 'Vascular',
        content: '参数量化结果',
      }, {
        filename: '0',
        content: '原图',
      }, {
        filename: '1',
        content: '分割结果',
      }, {
        filename: '2',
        content: '分级投影可视化',
      }, {
        filename: '2_1',
        content: '分级结果及概率',
      }, {
        filename: '3',
        content: '分级关注区域可视化',
      },{
        filename: 'XXX_tmp',
        content: '分割结果叠加在共焦影像上',
      }],
      dialogVisible: false,
      excel_state:false,
      Data1:[],
      Data2:[],
      Data3:[],
      Data4:[],
      Data5:[],
      Data6:[],
      upload_number: 3, // 上传线程数量限制，还没实现
      has_upload_count: 0, // 上传成功和失败都要更新，用于判断是否上传完成
      has_upload_fail: 0,
      activeName: 'first',
      tableData: [],
      url_messsge: '',
      left_time: '开始处理',
      left_time2: '下载图片',
      left_time3: '数据导出',
      search_img_name: '',
      server_url: 'http://114.55.245.149:8000',
      users_name: '协和眼科',
      currentPage1: '1',
      has_upload_count2: 0,
      qqq: '',
      json1: {},
      json2: {},
      json3: '',
      json4: '',
      json_1:'',
      json_2:'',
      json_3:'',
      json_4:'',
      picked: 'One',
      seg_pick: 'One',
      pick3: 'One',
      url_org: '',
      url_enh: '',
      url_seg_org: '',
      url_seg_enh: '',
      url_seg2_org: '',
      url_seg2_enh: '',
      url_grade_org: '',
      url_grade_enh: '',
      load: false,
      load2: false,
      load3: false,
      level_org1: '',
      level_org: '',
      level_enh: '',
      level_enh1: '',
      url_color_org: '',
      url_color_enh: '',
      url_point_org: '',
      url_point_enh: '',
      url_seg3_org: '',
      url_seg3_enh: '',
      vascular_org: '',
      vascular_enh: '',
      url_org_list: '',
      radio: 'normal',
      probl: '',
      probl1: '',
      probl3: '',
      probl4: '',
      link_dic: {
        'normal': 0,
        'first': 1,
        'second': 2,
        'third': 3,
        'forth': 4
      },
      // 文件上传部分
      fileList: [],
      url: {
        upload: 'http://114.55.245.149:8000/app/multiupload',
        start_predict: 'http://114.55.245.149:8000/app/preditstart',
        image_get: 'http://114.55.245.149:8000/app/predict_get',
        down_load: 'http://114.55.245.149:8000/app/multi_download_label',
        state_get: 'http://114.55.245.149:8000/app/longTaskStateGet',
        upload_data: {
          user_name: '',
          token: '',
          language:''
        },
        upload_img_name: 'image'

      },
      state_monitor: {
        file_name: [],
        has_finished: false,
        state: ''
      },
      // 树形结构
      tree_data: [], // {label: xx, children: []}

      // 下拉框
      options: [
        {
          value: 0,
          label: '处理'
        },
        {
          value: -1,
          label: '不处理'
        }
      ],
      option1: [
        {
          value: 0,
          label: 'CS-Net'
        },
        {
          value: 1,
          label: 'NerveFormer'
        },
        {
          value: 2,
          label: 'CS-Net_DC'
        },
        {
          value: 3,
          label: 'NerveFormer_DC'
        }
      ],
      option2: [
        {
          value: 0,
          label: '处理'
        },
        {
          value: -1,
          label: '不处理'
        }
      ],
      option3: [
        {
          value: 0,
          label: '处理'
        },
        {
          value: -1,
          label: '不处理'
        }
      ],
      search_id: '',
      // 提交处理请求
      deal_request: {
        enhance_choice: 0,
        segmentation_choice: 0,
        grade_choice: 0,
        vascular_choice: 0

      }
    }
  },
  watch: {
    // 根据名称筛选部门树
    qqq (val) {
      this.$refs.tree.filter(val)
    }
  },
  computed: {
    // 计算属性的 getter
    getFileListLength: function () {
      // `this` 指向 vm 实例
      return this.fileList.length
    }
  },
  mounted () {
    this.drawprob()
    this.drawprob1()
    const timer = setInterval(() => {
      // 这里调用调用需要执行的方法，1为自定义的参数，由于特殊的需求它将用来区分，定时器调用和手工调用，然后执行不同的业务逻辑
      this.time_get_img()
    }, 5000) // 每两秒执行1次
    this.$once('hook:beforeDestroy', () => {
      // 在页面销毁时，销毁定时器
      clearInterval(timer)
    })
  },

  filters: {
    // 当标题字数超出时，超出部分显示’...‘。此处限制超出8位即触发隐藏效果
    ellipsis (value) {
      if (!value) return ''
      if (value.length > 17) {
        return value.slice(0, 17) + '...'
      }
      return value
    }
  },

  methods: {
    //选择下载方式
    handleCommand(command) {
      if(command == 'a'){
        this.url.upload_data.language = 'CHI'
        this.image_download()}
      else if (command == 'b'){
        this.url.upload_data.language = 'ENG'
        this.image_download()
      }
    },
    //导出按钮
    async btnClickExport() {
      // debugger
      if (this.tree_data.length === 0) {
        this.$modal.msgError('请先上传图片')
        return
      }
      if (this.has_upload_count < this.fileList.length) {
        this.$modal.msgError('请先上传图片')
        return
      }
      if (this.excel_state === false) {
        this.$modal.msgError('等待处理完成')
        return
      }
      this.button_clock_start3()
      for (let i = 0; i < this.tree_data.length; ++i) {
        let each_message = this.tree_data[i].label
        await this.request_img2(each_message)
        let obj = new Object();
        obj["图片名"] = each_message;
        obj["弯曲度概率"] = this.level_org1.probabilities;
        obj["弯曲度分级"] = this.level_org1.level;
        this.Data1.push(obj);
        let obj1 = new Object();
        obj1["图片名"] = each_message;
        obj1["弯曲度概率"] = this.level_enh1.probabilities;
        obj1["弯曲度分级"] = this.level_enh1.level;
        this.Data2.push(obj1);
        let obj2 = new Object();
        obj2["图片名"] = each_message;
        obj2["CNFL"] = this.json_1.CNFL;
        obj2["CNFD"] = this.json_1.CNFD;
        obj2["CTBD"] = this.json_1.CTBD;
        obj2["CNBD"] = this.json_1.CNBD;
        this.Data3.push(obj2);
        let obj3 = new Object();
        obj3["图片名"] = each_message;
        obj3["CNFL"] = this.json_2.CNFL;
        obj3["CNFD"] = this.json_2.CNFD;
        obj3["CTBD"] = this.json_2.CTBD;
        obj3["CNBD"] = this.json_2.CNBD;
        this.Data4.push(obj3);
        let obj4 = new Object();
        obj4["图片名"] = each_message;
        obj4[" 0"] = this.json_3.y[0];
        obj4[" 20"] = this.json_3.y[1];
        obj4[" 40"] = this.json_3.y[2];
        obj4[" 60"] = this.json_3.y[3];
        obj4[" 80"] = this.json_3.y[4];
        obj4[" 100"] = this.json_3.y[5];
        obj4[" 120"] = this.json_3.y[6];
        obj4[" 140"] = this.json_3.y[7];
        obj4[" 160"] = this.json_3.y[8];
        obj4[" 180"] = this.json_3.y[9];
        this.Data5.push(obj4);
        let obj5 = new Object();
        obj5["图片名"] = each_message;
        obj5[" 0"] = this.json_4.y[0];
        obj5[" 20"] = this.json_4.y[1];
        obj5[" 40"] = this.json_4.y[2];
        obj5[" 60"] = this.json_4.y[3];
        obj5[" 80"] = this.json_4.y[4];
        obj5[" 100"] = this.json_4.y[5];
        obj5[" 120"] = this.json_4.y[6];
        obj5[" 140"] = this.json_4.y[7];
        obj5[" 160"] = this.json_4.y[8];
        obj5[" 180"] = this.json_4.y[9];
        this.Data6.push(obj5);
      }

      // this.reportsDataTitle =[] 数据格式在下面
      var normal = this.Data1;
      var enhance = this.Data2;//表格
      var normal_1 = this.Data3;//表格
      var enhance_1 = this.Data4;//表格
      var normal_2 = this.Data5;//表格
      var enhance_2 = this.Data6;//表格
      var sheet1 = XLSX.utils.json_to_sheet(normal);
      var sheet2 = XLSX.utils.json_to_sheet(enhance);
      var sheet3 = XLSX.utils.json_to_sheet(normal_1);
      var sheet4 = XLSX.utils.json_to_sheet(enhance_1);
      var sheet5 = XLSX.utils.json_to_sheet(normal_2);
      var sheet6 = XLSX.utils.json_to_sheet(enhance_2);

      var wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, sheet1, "原图 弯曲度检测");
      XLSX.utils.book_append_sheet(wb, sheet2, "增强图 弯曲度检测");
      XLSX.utils.book_append_sheet(wb, sheet3, "原图 血管量化");
      XLSX.utils.book_append_sheet(wb, sheet4, "增强图 血管量化");
      XLSX.utils.book_append_sheet(wb, sheet5, "原图 神经方向角度");
      XLSX.utils.book_append_sheet(wb, sheet6, "增强图 神经方向角度");
      const workbookBlob = this.workbook2blob(wb);

      //获取当前时间
      var date = new Date();
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      var hours = date.getHours();
      var minute = date.getMinutes();
      var second = date.getSeconds();

      var nowDate = year.toString() + month.toString() + day.toString() + hours.toString() + minute.toString() + second.toString();

      this.openDownloadDialog(workbookBlob, '量化指标' + nowDate + '.xlsx');
    },
    workbook2blob(workbook) {
      // 生成excel的配置项
      var wopts = {
        // 要生成的文件类型
        bookType: "xlsx",
        // // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
        bookSST: false,
        type: "binary"
      };
      var wbout = XLSX.write(workbook, wopts);
      // 将字符串转ArrayBuffer
      function s2ab(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
      }
      var blob = new Blob([s2ab(wbout)], {
        type: "application/octet-stream"
      });
      return blob;
    },
    openDownloadDialog(blob, fileName) {
      if (typeof blob == "object" && blob instanceof Blob) {
        blob = URL.createObjectURL(blob); // 创建blob地址
      }
      var aLink = document.createElement("a");
      aLink.href = blob;
      // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，有时候 file///模式下不会生效
      aLink.download = fileName || "";
      var event;
      if (window.MouseEvent) event = new MouseEvent("click");
      //   移动端
      else {
        event = document.createEvent("MouseEvents");
        event.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
      }
      aLink.dispatchEvent(event);
    },
    //  上传进度条
    setItemProgress (planNum, completeNum) {
      if (planNum > completeNum) {
        return 100
      } else {
        return parseInt((planNum / completeNum).toFixed(1) * 100)
      }
    },
    setItemText (planNum, completeNum, failnumber) {
      return () => {
        return '已上传： ' + planNum + '，上传总数： ' + completeNum + '，上传失败：' + failnumber
      }
    },

    setItemStatus (planNum, completeNum) {
      if (planNum > completeNum) {
        return 'exception'
      } else if (planNum === completeNum) {
        return 'success'
      } else {
        return 'warning'
      }
    },
    handleUploadSuccess () {
      this.fileList = []
    },
    handleClick (tab, event) {
      console.log(tab, event)
    },
    // 效率监控
    predictStateMonitor () {
      if (this.tree_data.length === 0) {
        this.$modal.msgError('请先上传图片')
        return
      }
      if (this.has_upload_count < this.fileList.length) {
        this.$modal.msgError('请先上传图片')
        return
      }
      this.button_clock_start()
      let param = new FormData()
      param.append('user_name', this.url.upload_data.user_name)
      param.append('token', this.url.upload_data.token)
      param.append('data', JSON.stringify(this.deal_request))

      let config = {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      }
      let that = this

      axios.post(this.url.start_predict,
        param, config
      ).then((res) => {
        let json = res.data
        // eslint-disable-next-line camelcase
        let redis_id = json['id']
        let result = json['result']
        if (result === false) {
          this.$modal.msgError('a task is processing, waiting!!!!')
          return
        }

        that.$modal.msgSuccess('request upload, waiting!!!')

        let time = setInterval(() => {
          let p = new FormData()
          p.append('redis_id', redis_id)
          axios.post(this.url.state_get, p, config).then(res => {
            let data = res.data
            data = data['message']
            let file_name = data['file_name']
            let has_finished = data['has_finished']
            let state = data['state']

            let change = false
            if (state.indexOf('error') !== -1) {
              this.$modal.msgError(state +
                ' predict process broken, please re-upload img and predict once more !!!' +
                'else upload img to us to debugger, Thanks!!!')
              clearInterval(time)
              return
            }
            if (state !== that.state_monitor.state) {
              that.state_monitor.state = state
              change = true
            }

            if (file_name !== that.state_monitor.file_name) {
              that.state_monitor.file_name = file_name
              change = true
            }

            if (has_finished !== that.state_monitor.has_finished) {
              that.state_monitor.has_finished = has_finished
              change = true
            }

            if (change) {
              that.$modal.msgSuccess(`processing_img: ${file_name}\n,
              processing_step: ${state}`)
            }

            if (has_finished) {
              this.$modal.msgSuccess('\n task has done')
              this.$notify({
                customClass:'fontclass',
                title: '处理完成',
                duration: 0,
                message:'可以继续点击下载或导出',
                type: 'success',
                offset: 100,
              })
              this.excel_state = true
              clearInterval(time)
            }
          })
        }, 1000)
      })
    },
    drawprob () {
      let prob = this.$echarts.init(document.getElementById('prob'))
      // 绘制图表
      // eslint-disable-next-line eqeqeq

      // eslint-disable-next-line camelcase
      let option_prob = {
        title: { text: '血管量化指标' },
        tooltip: {},
        legend: {
          show: 'true',
          data: ['增强前', '增强后']
        },
        xAxis: {
          data: ['CNFL', 'CNFD', 'CTBD', 'CNBD']
        },
        yAxis: [{
          type: 'value',
          max: 150,
          axisLabel: {
            show: true,

            interval: 'auto',
            formatter: function (value, index) {
              return value
            }
          },
          name: '对应值',
          show: true }, {
          type: 'value',
          max: 150,
          axisLabel: {
            show: true,

            interval: 'auto',
            formatter: function (value, index) {
              return value
            }
          },
          show: true }],
        series: [{
          yAxisIndex: 0,
          name: '增强前',
          type: 'bar',
          data: this.probl[this.link_dic[this.radio]],
          label: {
            normal: {
              show: true,
              position: 'top'
            }
          },
          itemStyle: {
            normal: {
              color: '#77caff'
            }
          }
        }, {
          yAxisIndex: 1,
          name: '增强后',
          type: 'bar',
          data: this.probl1[this.link_dic[this.radio]],
          label: {
            normal: {
              show: true,
              position: 'top'
            }
          },
          itemStyle: {
            normal: {
              color: '#e80a0a'
            }
          }
        }]
      }
      // eslint-disable-next-line eqeqeq
      prob.resize()
      prob.setOption(option_prob, true)
      console.log('prob_painted')
    },
    drawprob1 () {
      let prob = this.$echarts.init(document.getElementById('prob1'))
      // 绘制图表
      // eslint-disable-next-line eqeqeq

      // eslint-disable-next-line camelcase
      let option_prob = {
        title: { text: '神经方向直方图' },
        tooltip: {},
        legend: {
          show: 'true',
          data: ['增强前', '增强后']
        },
        xAxis: {
          data: ['0', '20', '40', '60', '80', '100', '120', '140', '160', '180']
        },
        yAxis: [{
          type: 'value',
          max: 30,
          axisLabel: {
            show: true,

            interval: 'auto',
            formatter: function (value, index) {
              return value
            }
          },
          name: '神经方向角度',
          show: true }, {
          type: 'value',
          max: 30,
          axisLabel: {
            show: true,

            interval: 'auto',
            formatter: function (value, index) {
              return value
            }
          },
          show: true }],
        series: [{
          yAxisIndex: 0,
          name: '增强前',
          type: 'bar',
          data: this.probl3[this.link_dic[this.radio]],
          label: {
            normal: {
              show: true,
              position: 'top'
            }
          },
          itemStyle: {
            normal: {
              color: '#77caff'
            }
          }
        }, {
          yAxisIndex: 1,
          name: '增强后',
          type: 'bar',
          data: this.probl4[this.link_dic[this.radio]],
          label: {
            normal: {
              show: true,
              position: 'top'
            }
          },
          itemStyle: {
            ormal: {
              color: '#e80a0a'
            }
          }
        }]
      }
      // eslint-disable-next-line eqeqeq
      prob.resize()
      prob.setOption(option_prob, true)
      console.log('prob1_painted')
    },
    //上传请求
    async postImgOfMy (options) {
      // 注意没有成功实现并发，只是对于过多的请求添加了随机时间
      // debugger
      let that = this
      that.fileList.push(options.file) // 莫名奇妙的bug

      const upload = async () => {
        that.upload_number -= 1
        let param = new FormData()
        param.append('user_name', options.data.user_name)
        param.append('token', options.data.token)
        param.append('image', options.file)

        let config = {
          headers: { 'Content-Type': 'multipart/form-data' }
        }
        let url = this.url.upload

        // 方案1， 添加等待队列
        // 方案2，增加一定超参数延迟，现在一起用
        LimitAxiosPost(url, param, config, (res) => {
          // debugger
          if (res.status === 200) {
            that.upload_success(res.data, options.file, that.fileList)
          } else {
            that.upload_error(res.data, options.file, that.fileList)
          }
        }, (res) => {
          // debugger
          that.has_upload_fail += 1
          that.has_upload_count += 1
          that.tableData.push({
            'file_name': options.file.name,
            'message': res.stack
          })
          that.$modal.msgError(options.file.name + '发生异常： ' + res.message)
        })
        // let res = await axios.post(url, param, config)
        // that.upload_number += 1
        // if (res.status == 200){
        //   // debugger
        //   that.upload_success(res.data, options.file, that.fileList)
        //   return res
        // }else{
        //   that.upload_error(res.data, options.file, that.fileList)
        //   return res
        // }
      }

      if (that.upload_number > 0) await upload()
      else setTimeout(() => { upload() }, Math.random() * 2500) // python小水管
    },

    getCurrentTime () {
      // 获取当前时间并打印
      if (this.users_name === '') {
        this.$modal.msgError('请先输入用户名')
        return
      }
      let _this = this
      let yy = new Date().getFullYear()
      let mm = new Date().getMonth() + 1
      let dd = new Date().getDate()
      let hh = new Date().getHours()
      let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
      let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
      _this.gettime = yy + '_' + mm + '_' + dd + '_' + hh + '_' + mf + '_' + ss
      this.url.upload_data.token = _this.gettime
      function b64Encode (str) {
        return btoa(encodeURIComponent(str))
      }
      // function b64Decode (str) {
      //   return decodeURIComponent(atob(str))
      // }
      this.url.upload_data.user_name = b64Encode(this.users_name)
      // console.log(b64Decode(strChinaBase64))
      this.tree_data = []
      this.has_upload_count = 0
      this.has_upload_count2 = 0
      this.search_value = 0
      this.Data1 = []
      this.Data2 = []
      this.Data3 = []
      this.Data4 = []
      this.Data5 = []
      this.Data6 = []
      // console.log(_this.gettime)
    },

    getSpellData (e) {
      // 返回的base64或者file结果
      console.log(e)
    },
    // 下载图片
    image_download () {
      if (this.tree_data.length === 0) {
        this.$modal.msgError('请先上传图片')
        return
      }
      if (this.has_upload_count < this.fileList.length) {
        this.$modal.msgError('请先上传图片')
        return
      }
      if (this.excel_state === false) {
        this.$modal.msgError('等待处理完成')
        return
      }
      this.dialogVisible = true
      this.button_clock_start2()
      let param = new FormData()
      param.append('user_name', this.url.upload_data.user_name)
      param.append('token', this.url.upload_data.token)
      param.append('language', this.url.upload_data.language)

      let config = {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; application/octet-stream' },
        responseType: 'blob'
      }
      axios.post(this.url.down_load,
        param, config
      ).then((res) => {
        // debugger
        const blob = new Blob([res.data], { type: 'application/zip' })
        // let decode_data = Base64.decode(res.data)
        let dispositon = decodeURI(res.headers['content-disposition'])
        let fileName = dispositon.substring(dispositon.indexOf('filename=') + 9, dispositon.length)

        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href)
        document.body.removeChild(elink)
      })
    },
    // 判断上传是否成功
    upload_success (response, file, fileList) {
      // debugger
      // console.log(response)
      this.has_upload_count += 1
      this.has_upload_count2 = this.fileList.length

      let status = response.result
      let message = response.message
      let file_name = file.name
      // console.log(fileList)

      if (!status) {
        this.$modal.msgError(file_name + '上传失败')
        return
      }
      for (let i = 0; i < message.length; ++i) {
        let each_message = message[i]
        if (each_message.name === file_name) {
          if (each_message['success'] === 'ok') {
            this.tree_data.push({
              'label': file_name,
              'value': this.search_value
            })
            this.search_value += 1
          } else {
            // debugger
            console.log('-----------')
            console.log(each_message)
            that.has_upload_fail += 1
            this.tableData.push({
              'file_name': file_name,
              'message': each_message['error']
            })
            this.$modal.msgError(file_name + '上传失败, 原因如下： ' + each_message['error'])
          }
        }
      }
      // debugger
      if (this.has_upload_count === this.fileList.length) {
        this.$modal.msgSuccess('上传完毕')
      }
    },
    // 筛选节点
    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    upload_error (response, file, fileList) {
      debugger
      let file_name = file.name
      this.has_upload_count2 = this.fileList.length
      this.$modal.msgError(file_name + '上传失败')
    },

    upload_image_list (file, fileList) {
      let temp_array = []
      for (let i = 0; i < fileList.length; ++i) {
        let each_file = fileList[i]
        temp_array.push(
          { label: each_file.name }
        )
      }
      // eslint-disable-next-line camelcase
      this.tree_data = temp_array
    },

    upload_change (file, fileList) {
      this.upload_image_list(file, fileList)
    },

    upload_remove (file, fileList) {
      this.upload_image_list(file, fileList)
    },
    button_clock_start () {
      this.load = true
      this.left_time = 120
      const t = setInterval(() => {
        this.left_time -= 1

        if (this.left_time === 0) {
          this.load = false
          this.left_time = '开始处理'
          clearInterval(t)
        }
      }, 1000) // 每两秒执行1次
    },
    button_clock_start2 () {
      this.load2 = true
      this.left_time2 = 120
      const t = setInterval(() => {
        this.left_time2 -= 1

        if (this.left_time2 === 0) {
          this.load2 = false
          this.left_time2 = '下载图片'
          clearInterval(t)
        }
      }, 1000) // 每两秒执行1次
    },
    button_clock_start3 () {
      this.load3 = true
      this.left_time3 = 120
      const t = setInterval(() => {
        this.left_time3 -= 1

        if (this.left_time3 === 0) {
          this.load3 = false
          this.left_time3 = '数据导出'
          clearInterval(t)
        }
      }, 1000) // 每两秒执行1次
    },

    // 删除文件
    remove (node, data) {
      const parent = node.parent
      const children = parent.data.children || parent.data
      const index = children.findIndex(d => d.id === data.id)
      children.splice(index, 1)
    },

    time_get_img () {
      // console.log('我是定时器')
      if (this.search_img_name === '') {

      } else {
        this.request_img(this.search_img_name)
      }
    },

    // 获得处理好的东西
    image_get (data,node) {
      // console.log("点击了", data)
      let image_name = data.label
      this.search_img_name = image_name
      this.request_img(image_name)
      let j = node.value
      this.search_id = j
    },

    request_img (image_name) {
      let param = new FormData()
      param.append('img_name', image_name)
      param.append('user_name', this.url.upload_data.user_name)
      param.append('token', this.url.upload_data.token)

      let config = {
        headers: { 'Content-Type': 'multipart/form-data' }
      }
      axios
        .post(this.url.image_get, param, config)
        .then(
          res => {
            this.url_org_list = res.data.segmentation.f2_1
            this.url_org = res.data.segmentation.f0[0]
            this.url_enh = res.data.segmentation.f0[1]
            this.url_seg_org = res.data.segmentation.f1[0]
            this.url_seg_enh = res.data.segmentation.f1[1]
            this.url_seg2_org = res.data.segmentation.f2[0]
            this.url_seg2_enh = res.data.segmentation.f2[1]
            this.url_grade_org = res.data.segmentation.f3[0]
            this.url_grade_enh = res.data.segmentation.f3[1]
            this.level_org = res.data.segmentation.f2_1[0]
            if (this.level_org !== '') {
              // eslint-disable-next-line no-eval
              this.level_org = eval('(' + this.level_org + ')')
              this.level_org.probabilities = (this.level_org.probabilities * 100).toFixed(2) + '%'
            } else this.level_org = {}
            this.level_enh = res.data.segmentation.f2_1[1]
            if (this.level_enh !== '') {
              // eslint-disable-next-line no-eval
              this.level_enh = eval('(' + this.level_enh + ')')
              this.level_enh.probabilities = (this.level_enh.probabilities * 100).toFixed(2) + '%'
            } else this.level_enh = {}
            this.url_color_org = res.data.vascular.f0[0]
            this.url_color_enh = res.data.vascular.f0[1]
            this.url_point_org = res.data.vascular.f1[0]
            this.url_point_enh = res.data.vascular.f1[1]
            this.url_seg3_org = res.data.vascular.f2[0]
            if (this.url_seg3_org !== '') {
              // eslint-disable-next-line no-eval
              this.json3 = eval('(' + this.url_seg3_org + ')')
            } else this.json3 = {}

            this.url_seg3_enh = res.data.vascular.f2[1]
            if (this.url_seg3_enh !== '') {
              // eslint-disable-next-line no-eval
              this.json4 = eval('(' + this.url_seg3_enh + ')')
            } else this.json4 = {}
            this.probl3 = [this.json3.y]
            this.probl4 = [this.json4.y]

            this.vascular_org = res.data.vascular.f2_1[0]
            if (this.vascular_org !== '') {
              // eslint-disable-next-line no-eval
              this.json1 = eval('(' + this.vascular_org + ')')
              for (let item in this.json1) {
                this.json1[item] = this.json1[item].toFixed(2)
              }
            } else this.json1 = {}

            this.vascular_enh = res.data.vascular.f2_1[1]
            if (this.vascular_enh !== '') {
              // eslint-disable-next-line no-eval
              this.json2 = eval('(' + this.vascular_enh + ')')
              for (let item in this.json2) {
                this.json2[item] = this.json2[item].toFixed(2)
              }
            } else this.json2 = {}
            this.probl = [[this.json1.CNFL, this.json1.CNFD, this.json1.CTBD, this.json1.CNBD]]
            this.probl1 = [[this.json2.CNFL, this.json2.CNFD, this.json2.CTBD, this.json2.CNBD]]
            this.drawprob()
            this.drawprob1()
            // console.log("查看回复")
            // console.log(res)
            // this.load = false
          }
        )
    },
    async request_img2 (image_name) {
      let param = new FormData()
      param.append('img_name', image_name)
      param.append('user_name', this.url.upload_data.user_name)
      param.append('token', this.url.upload_data.token)

      let config = {
        headers: { 'Content-Type': 'multipart/form-data' }
      }
      await axios
        .post(this.url.image_get, param, config)
        .then(
          res => {
            this.level_org1 = res.data.segmentation.f2_1[0]
            if (this.level_org1 !== '') {
              // eslint-disable-next-line no-eval
              this.level_org1 = eval('(' + this.level_org1 + ')')
              this.level_org1.probabilities = (this.level_org1.probabilities * 100).toFixed(2) + '%'
            } else this.level_org1 = {}
            this.level_enh1 = res.data.segmentation.f2_1[1]
            if (this.level_enh1 !== '') {
              // eslint-disable-next-line no-eval
              this.level_enh1 = eval('(' + this.level_enh1 + ')')
              this.level_enh1.probabilities = (this.level_enh1.probabilities * 100).toFixed(2) + '%'
            } else this.level_enh1 = {}
            this.json_3 = res.data.vascular.f2[0]
            if (this.json_3 !== '') {
              // eslint-disable-next-line no-eval
              this.json_3 = eval('(' + this.json_3 + ')')
            } else this.json_3 = {}

            this.json_4 = res.data.vascular.f2[1]
            if (this.json_4 !== '') {
              // eslint-disable-next-line no-eval
              this.json_4 = eval('(' + this.json_4 + ')')
            } else this.json_4 = {}

            this.json_1 = res.data.vascular.f2_1[0]
            if (this.json_1 !== '') {
              // eslint-disable-next-line no-eval
              this.json_1 = eval('(' + this.json_1 + ')')
              for (let item in this.json_1) {
                this.json_1[item] = this.json_1[item].toFixed(2)
              }
            } else this.json_1 = {}

            this.json_2 = res.data.vascular.f2_1[1]
            if (this.json_2 !== '') {
              // eslint-disable-next-line no-eval
              this.json_2 = eval('(' + this.json_2 + ')')
              for (let item in this.json_2) {
                this.json_2[item] = this.json_2[item].toFixed(2)
              }
            } else this.json_2 = {}
          }
        )
    }
  }
}
</script>

<style lang="scss" scoped>

.fontclass{
  font-family:"PingFang SC";
  font-size: large;
  font-weight: bold;
}
.one{
  color:black;
  margin-left:20px;
}
.item{
}

.upload-demo{
  height: 90px;
}

.chosen{
  margin-top: 5%;
}

.button{

  display: flex;
  flex-direction:column;
  justify-content: space-around;
  align-items:start;
}
.button1{

  display: flex;
  flex-direction:column;
  justify-content: space-around;
  align-items:start;
}
.card1{
  height: 15%;
  margin-top: 3%;
  margin-bottom: 3%;
}
.card2{
  height: 80%;
  padding-bottom: 1%;
}
.card5{
  height: 80%;
  margin-top: 1%;
  padding-bottom: 1%;
}
.card3{
  height: 12%;
  margin-top: 1%;
  padding-bottom: 5%;
}
.card4{
  height: 80%;
  margin-top: 1%;
}
.option{
  height: 40%;

  display: flex;
  flex-direction:row;
  flex-wrap: nowrap;
  margin-left: 0;
  align-items:center;
}
.col1{
  flex:1;
  display: flex;
  flex-direction:column;
  flex-wrap: nowrap;
  justify-content:space-around;
  align-items:flex-start;
}
.col2{
  flex:5;
  display: flex;
  flex-direction:column;
}
.body1{
  display: flex;
  flex-direction:column;
  justify-content: space-around;
  align-items:flex-start;
}
.body2{
  display: flex;
  flex-direction:row;
  align-items: center;
  justify-content: space-around;
}
.body3{
  display: flex;
  flex-direction:row;
  align-items: flex-start;
}
.input{
  margin-top: 5%;
  margin-bottom: 5%;
  display: flex;
  flex-direction:column;
  align-items: center;
  justify-content: space-around;
}
.corneal{
  display: flex;
  flex-direction:row;
  flex-wrap: wrap;

}
.dd{
  width: 100%;
  display: flex;
  flex-direction:column;
  align-items:center;
}
.demo-image__preview {
  width: 80%;
  aspect-ratio: 1 / 1;
  float: left;
  align-content: center;
  display: flex;
  flex-direction:column;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.09);
}
.o-image__preview {
  width: 55%;
  aspect-ratio: 1 / 1;
  float: left;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.09);
}
.info_1 {
  margin-top: 5%;
  text-align: center;
  white-space: nowrap;
  background-color: unset;
  width: 70%;
}
.info_2 {
  white-space: nowrap;
  text-align: center;

  background-color: unset;
  width: 55%;
  margin-bottom: 10%;
}
.image {
  aspect-ratio: 1 / 1;
  background-color: unset;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.09);
  display: flex;
  justify-content: center;
  align-items:center;
}
.image_1 {
  aspect-ratio: 1 / 1;
  background-color: unset;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.09);
}

.result1{
  display: flex;
  flex-direction:column;
  align-items:center;
}
.result2{
  display: flex;
  flex-direction:column;
  align-items:center;
}
.result3{
  display: flex;
  flex-direction:column;
  align-items:center;
}
.result4{
  display: flex;
  flex-direction:column;
  align-items:center;
}
.row{
  flex: 1;
  height: 30%;
  width: 100%;
  display: flex;
  flex-direction:row;
  align-items: center;
  justify-content: space-around;
  margin-bottom: 10%;
}
.pic{
  flex: 1;

  flex-direction:column;
  justify-content:space-around;
  align-items:center;
}
.app-container {
  padding: 20px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}
.el-icon-arrow-down {
  font-size: 12px;
}
</style>
